/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controller;

import com.exception.DataException;
import com.javabeans.*;
import com.util.*;
import com.model.*;
import com.db.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.Calendar;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrador
 */
public class InfAcademicaDoc extends HttpServlet {

    HttpServletRequest request;
    HttpServletResponse response;
    HttpSession session;
    String msg = "";
    
    private String PAGE = "";
    private static final String ERROR_PAGE = "WEB-INF/error.jsp";
    private static final String ERROR_AJAX = "WEB-INF/errorAjax.jsp";
    boolean isForward = true; // inicializamos con forward....
    Usuario s_Docente = null;
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        this.request = request;
        this.response = response;
        session = request.getSession();
        int accion = Integer.parseInt(request.getParameter("accion"));        
        if(session.getAttribute("s_docente") != null){
            s_Docente = (Usuario)session.getAttribute("s_docente");
            try{
                switch(accion){
                    case 1 : formHorarios(); break;                           // accion = 1 = inicio para ver horarios
                    case 2 : verHorarios(); break;                           // accion = 1 = inicio para ver horarios
                    default : System.out.println(" accion = "+accion+" no existe en Docentes.java"); throw new DataException("accion = "+accion+" no existe en Docentes.java");
                }
            }catch(DataException e){
                throw new ServletException(e);
            }
        }else
            PAGE = "web/index.jsp?msg=Indentifiquese. La Session no existe!";
        if(PAGE.length() > 0){
            if(isForward){
                RequestDispatcher dispatch = request.getRequestDispatcher(PAGE);
                dispatch.forward(request,response);
            }else{
                response.sendRedirect(PAGE);
            }
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void formHorarios() throws DataException{
        Connection c = null;
        try{
            c = Conector.getConexion();
            GestionManager gmanager = ManagerFactory.getGestionManagerInstance(c);
            FacultadManager fmanager = ManagerFactory.getFacultadManagerInstance(c);
            List<Facultad> facultades = fmanager.getFacultadesPorDocente(s_Docente.getIdUsuario());
            Calendar hoy = Calendar.getInstance();
            int year = hoy.get(Calendar.YEAR) - 15;            
            request.setAttribute("facultades", facultades);
            request.setAttribute("gestiones", gmanager.getGestionesBasicByYear(year));
            PAGE = "WEB-INF/DOCENTE/infoAcademica/horarios/verHorario.jsp";
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() DataException "+e.getMessage());
            PAGE = ERROR_PAGE;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() Exception ex: "+ex.getMessage());
            PAGE = ERROR_PAGE;
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
    public void verHorarios()throws DataException{// accion = 2 = muestra los horarios
        PAGE = ""; // funcion ajax
        Connection c = null;
        int idDocente = s_Docente.getIdUsuario();
        try{
            int idFacultad = Integer.parseInt(request.getParameter("idFacultad"));
            String nomFacultad = request.getParameter("nomFacultad");
            int idGestion = Integer.parseInt(request.getParameter("idGestion"));
            String nomGestion = request.getParameter("nomGestion");
            c = Conector.getConexion();
            GrupoHorarioManager ghmanager = ManagerFactory.getGrupoHorarioManagerInstance(c);
            MateriaManager mmanager = ManagerFactory.getMateriaManagerInstance(c);
            DiaSemanaManager dsmanger = ManagerFactory.getDiaSemanaManagerInstance(c);
            PeriodoDiaManager pdmanager = ManagerFactory.getPeriodoDiaManagerInstance(c);
            HorarioManager hmanager = ManagerFactory.getHorarioManagerInstance(c);
            
            List<GrupoHorario> ghorarios = ghmanager.getHorariosGrupos(idFacultad, idGestion, idDocente);
            List<PeriodoDia> periodosDia = pdmanager.getPeriodosDia(idFacultad);
            List<DiaSemana> diasSemana = dsmanger.getDiasHorario();
            List<Horario> horarios = hmanager.getHorariosBasic(idFacultad);
            
            // IMPRIMIMOS EL RESULTADO DE LA TRANSACCION
            PrintWriter out = response.getWriter();
            out.println("<h2 class='decorado'>Horarios Gesti&oacute;n ''"+nomGestion+"''</h2>");
            out.println("<table class='tabla_decorado' style='width: 100%'>");
            int i = 0;
            int j = 0;
            int idD = 0;
            int idP = 0;
            int sizeD = diasSemana.size();
            boolean flag = false;
            String aux = "";
            if(periodosDia.size() > 0){
                for(PeriodoDia pd : periodosDia){
                    idP = pd.getIdPeriodoDia();
                    if(i == 0){
                        out.println("<thead>");
                        out.println("    <tr>");
                        out.println("        <th width='8%' class='th_decoradoRowspan'>&nbsp;</th>");
                        for(DiaSemana ds : diasSemana){
                            out.println("<th width='"+(92/sizeD)+"%' class='th_decoradoRowspan'>"+ds.getNombre()+"</th>");
                        }
                        out.println("    </tr>");
                        out.println("</thead>");
                        out.println("<tbody>");
                    }
                    j = 0;
                    // tr_decoradoRowspan
                    out.println("<tr class='tr_decoradoRowspan'>");
                    while(j < sizeD){
                        if(j == 0)
                            out.println("<td class='td_decoradoRowspan' align='center'>"+pd.getHoraIni()+" - "+pd.getHoraFin()+"</td>");
                        DiaSemana ds = (DiaSemana)diasSemana.get(j);
                        idD = ds.getIdDiaSemana();
                        flag = false;
                        aux = "";
                        for(Horario h : horarios){
                            if(idD == h.getIdDiaSemana() && idP == h.getIdPeriodoDia()){
                                flag = true;
                                for(GrupoHorario gh:ghorarios){
                                    if(idD == gh.getIdDiaSemana() && idP == gh.getIdPeriodoDia()){
                                        List<Materia> materias = mmanager.getMateriasPorGrupo(idGestion, gh.getIdGrupo());
                                        for(Materia m:materias){
                                            aux += m.getNombre()+" ("+m.getCarrera().getSigla()+")<br/>";
                                        }
                                        aux += "Grupo: "+gh.getAux()+"<br/>";
                                        aux += "Aula: "+gh.getAula().getNro()+"<br/>";
                                        aux += "Desc: "+gh.getAula().getDescripcion()+"<br/>";
                                    }
                                }
                            }
                        }
                        if(flag)
                            out.println("<td class='td_decoradoRowspan' align='center' style='background:#E5FFE5'>"+aux+"</td>");
                        else
                            out.println("<td class='td_decoradoRowspan' align='center'>&nbsp;</td>");
                        j++;
                    }
                    out.println("</tr>");
                    i++;
                } // fin for
            }else{
                out.println("<tr class='tr_decoradoRowspan'>");
                out.println("   <td class='td_decoradoRowspan' style='text-align:center;color:red'>No existen periodos del d&iacute;a!</td>");
                out.println("</tr>");
            }
            out.println("        </tbody>");
            out.println("</table>");
            out.close();           
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() DataException "+e.getMessage());
            PAGE = ERROR_AJAX;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" InfAcademicaDoc -> verHorarios() Exception ex: "+ex.getMessage());
            PAGE = ERROR_AJAX;
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    
}
